const axios = require("axios");
const WinexAuthorizationGenerator = require("../WinexAuthorizationGenerator");
const WinexRoomGenerator = require("./WinexRoomGenerator");

class WinexInpatientBaseGenerator {

    constructor(redisHost = "127.0.0.1", redisPort = 6379, redisDb = 0) {
        this.redisHost = redisHost;
        this.redisPort = redisPort;
        this.redisDb = redisDb;
        this.authorization = null;
    }

    /**
     * 
     * @param {{wardId: string, wardNumber: string, wardName: string}} ward 
     * @returns {Promise<{wardId: string, wardNumber: string, wardName: string, roomId: string, roomNumber: string, roomName: string, bedId: string, bedNumber: string, departmentId: string, departmentName: string}[]>}
     */
    async getBeds(ward) {
        const winexAuthorizationGenerator = new WinexAuthorizationGenerator();
        this.authorization = await winexAuthorizationGenerator.getAuthorization("adminAuthorizations");
        const url = `${this.authorization.hostname}/mdm-nurse/api/v1/app_execute_mdm/inpatient/inpatient_bed/query/by_example`;
        const data = JSON.stringify(
            {
                "pageNo": 0,
                "pageSize": 500,
                "pageType": "P",
                "wardId": ward.wardId,
                "bedTypeCode": "",
                "roomName": "",
                "bedNo": "",
                "inpatRoomId": "",
                "bedEnabledFlag": "",
                "bedDeptId": ""
            }
        );
        const config = {
            method: "post",
            maxBodyLength: Infinity,
            url: url,
            headers: {
                "Content-Type": "application/json",
                "Authorization": this.authorization.authorization,
            },
            data: data,
        };
        if (config.url.startsWith("https://")) {
            config.httpsAgent = new (require("https").Agent)({ rejectUnauthorized: false });
        }
        const response = await axios.request(config);
        let beds = response.data.data.map(bed => {
            return {
                wardId: ward.wardId,
                wardNumber: ward.wardNumber,
                wardName: ward.wardName,
                roomId: bed.inpatRoomId,
                roomNumber: "",
                roomName: bed.roomName,
                bedId: bed.inpatBedServiceId,
                bedNumber: bed.bedNo,
                departmentId: bed.bedDeptId,
                departmentName: bed.bedDeptName,
            }
        })
        return beds;
    }

    /**
     * 
     * @param {{wardId: string, wardNumber: string, wardName: string}} ward 
     * @param {number} numberOfBeds 
     * @param {string} bedNumberPrefix 
     * @param {{departmentId: string, departmentNumber: string, departmentName: string}} department 
     * @returns {Promise<{wardId: string, wardNumber: string, wardName: string, roomId: string, roomNumber: string, roomName: string, bedId: string, bedNumber: string}[]>}
     */
    async create(ward, numberOfBeds, bedNumberPrefix = "", department = null) {
        const winexAuthorizationGenerator = new WinexAuthorizationGenerator();
        this.authorization = await winexAuthorizationGenerator.getAuthorization("adminAuthorizations");
        const winexRoomGenerator = new WinexRoomGenerator(this.hostname);
        const rooms = await winexRoomGenerator.getRooms(ward);
        const beds = [];
        for (let i = 0; i < rooms.length; i++) {
            for (let j = 0; j < numberOfBeds; j++) {
                const room = rooms[i];
                beds.push({
                    "wardId": room.wardId,
                    "inpatRoomId": room.roomId,
                    "bedTList": [],
                    "bedNo": `${bedNumberPrefix}${String(beds.length + 1).padStart(3, "0")}`,
                    "bedTypeCode": "959851",
                    "currentNurseId": "",
                    "currentDoctorId": "",
                    "nurseGroupId": "",
                    "medicalGroupId": "",
                    "bedAgeTypeCode": "",
                    "bedSexTypeCode": "",
                    "bedDeptId": department ? department.departmentId : "",
                    "qcNurseId": "",
                    "deliverAppointmentFlag": "98176",
                    "memo": "",
                    "laterAdmittedToWardFlag": "98176",
                    "inpatBedParticipantList": []
                });
            }
        }
        const url = `${this.authorization.hostname}/mdm-nurse/api/v1/app_execute_mdm/inpatient/inpatient_bed/save`;
        const data = JSON.stringify(beds);
        const config = {
            method: "post",
            maxBodyLength: Infinity,
            url: url,
            headers: {
                "Content-Type": "application/json",
                "Authorization": this.authorization.authorization,
            },
            data: data,
        };
        if (config.url.startsWith("https://")) {
            config.httpsAgent = new (require("https").Agent)({ rejectUnauthorized: false });
        }
        const response = await axios.request(config);
        if (response.data.success) {
            return await this.getBeds(ward);
        }
        return [];
    }

    /**
     * 
     * @param {{wardId: string, wardNumber: string, wardName: string}} ward 
     */
    async setBedChargeServices(ward) {
        const winexAuthorizationGenerator = new WinexAuthorizationGenerator();
        this.authorization = await winexAuthorizationGenerator.getAuthorization("adminAuthorizations");
        let url = `${this.authorization.hostname}/mdm-nurse/api/v1/app_execute_mdm/inpatient/bed_charge/query/by_example`;
        let data = JSON.stringify({
            "pageType": "A"
        });
        let config = {
            method: "post",
            maxBodyLength: Infinity,
            url: url,
            headers: {
                "Content-Type": "application/json",
                "Authorization": this.authorization.authorization,
            },
            data: data,
        };
        if (config.url.startsWith("https://")) {
            config.httpsAgent = new (require("https").Agent)({ rejectUnauthorized: false });
        }
        let response = await axios.request(config);
        let encChargeServiceId = response.data.data[0].encChargeServiceId;
        url = `${this.authorization.hostname}/mdm-nurse/api/v1/app_execute_mdm/inpatient/bed_related_charge_svc/save`;
        data = JSON.stringify({
            "bedChargeServices": [
                {
                    "enabledFlag": "98175",
                    "encChargeServiceId": encChargeServiceId,
                    "encChargeServiceQty": 1
                }
            ],
            "bindingScopes": [
                {
                    "ids": [
                        ward.wardId
                    ],
                    "scope": 1
                }
            ],
            "isBatch": 1
        });
        config = {
            method: "post",
            maxBodyLength: Infinity,
            url: url,
            headers: {
                "Content-Type": "application/json",
                "Authorization": this.authorization.authorization,
            },
            data: data,
        };
        if (config.url.startsWith("https://")) {
            config.httpsAgent = new (require("https").Agent)({ rejectUnauthorized: false });
        }
        await axios.request(config);
    }

}

module.exports = WinexInpatientBaseGenerator;